package util

import (
	"gin_blog/pkg/setting"
	"github.com/dgrijalva/jwt-go"
	"time"
)

var jwtSecret = []byte(setting.AppSetting.JwtSecret)

type Claims struct {
	Phone string `json:"phone"`
	Password string `json:"password"`
	jwt.StandardClaims
}

func GenerateToken(phone, password string) (string, error) {
	nowTime :=time.Now()
	claims := Claims{
		phone,
		password,
		jwt.StandardClaims{
			ExpiresAt: nowTime.Add(time.Hour*8).Unix(),
			Issuer:"huangzhe",
		},
	}
	tokenClaims :=jwt.NewWithClaims(jwt.SigningMethodHS256,claims)
	token,err :=tokenClaims.SignedString(jwtSecret)
	return token,err
}

func ParseToken(token string) (*Claims, error) {
	tokenClaims,err :=jwt.ParseWithClaims(token,&Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})
	if tokenClaims !=nil{
		if claims,ok :=tokenClaims.Claims.(*Claims);ok&&tokenClaims.Valid{
			return claims, nil
		}
	}
	return nil, err
}